<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 专家委员会管理编辑 -->
    <a-form-model class="updateServiceDemand"
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 ? {} : rules"
    >
      <a-spin :spinning="loading">
        <!-- 表单 -->
        <a-card :bordered="false">
          <title-name title="基本信息"></title-name>
          <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''"
                       @selectOrg="selectOrg" @handleChange="getProjectInfo">
          </custom-form>
        </a-card>
        <a-card :bordered="false">
          <title-name title="个人业绩及成果"></title-name>
          <custom-form :formList="formListTwo" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''" >
          </custom-form>
        </a-card>
        <a-card :bordered="false">
          <title-name title="工作经历"></title-name>
          <a-button type="primary" @click="visible.visibleWork=true" v-if="editModel != 0">添加</a-button>
           <a-table :columns="columns" :data-source="form.workExperienceList" bordered style="margin-top:20px">
            <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
            <span slot="monitoringTime" slot-scope="text, record">{{ record.monitoringTime[0] }}~{{record.monitoringTime[1]}}</span>
            <span slot="action" slot-scope="text, record, index">
              <template>
                <a @click="delwork(index)" v-if="editModel!==0">删除</a>
              </template>
            </span>
          </a-table>
        </a-card>
         <a-card :bordered="false" v-if="editModel*1!==2">
          <title-name title="服务记录"></title-name>
          <!-- 表格 -->
            <s-table
                ref="table"
                tableLayout="fixed"
                size="default"
                rowKey="id"
                :columns="columnsService"
                :data="loadData"
                :page-keys="['pageNo', 'pageSize']"
                :alert="true"
                show-size-changer
                show-quick-jumper
                showPagination="auto">
                <template slot="evaluationId" slot-scope="text, record">
                {{getEvaluationName(record.evaluationId)}}
                </template>
            </s-table>
        </a-card>
        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top" v-if="editModel != 0">
          <a-button
            class="button_right"
            type="primary"
            :loading="loadingBtn.SUBMITTED"
            @click="handleSubmit('SUBMITTED')"
            >提交</a-button
          >
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
         <div class="btn_box page-btn-right-top" v-else>
        <a-button  @click="handleActiveClose">关闭</a-button>
      </div>
      </a-spin>
    </a-form-model>
      <DialogForm
          ref="dialogForm"
          edit-model="E"
          :custom-footer="true"
          :visible.sync="visible.visibleWork"
          :header-title="'工作经历'"
          :width="500"
          :form="workForm"
          :form-list="formListWork"
          :rules="rulesWork"
          @confirm="confirmWork">

          <template slot="footer">
            <a-button class="mr10p" :disabled="loading.subChangeCycle" @click="visible.visibleWork=false"> 取消 </a-button>
            <a-button type="primary" :loading="loading.subChangeCycle" @click="handleOk"> 提交 </a-button>
          </template>
        </DialogForm>
     
  </base-breadcrumb>
</template>

<script>
import { addExpert, getExpertDetail,getSerDataList} from '@/api/technical/expert'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司项目
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople' //联系人项目加岗位
import {genderList, educationList, jobStatusList } from './model'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import { getAllBranchCompany } from '@/api/commons'
import DialogForm from '@/components/DialogForm' // 弹窗
const columns = [
  { title: '序号', dataIndex: 'serial', width: 65, scopedSlots: { customRender: 'serial' } },
  { title: '起止时间', dataIndex: 'monitoringTime', width: '300px', scopedSlots: { customRender: 'monitoringTime' } },
  { title: '工作单位', dataIndex: 'workOrgInfo', ellipsis: true },
  { title: '职务', dataIndex: 'jobTitle', width: '280px', ellipsis: true },
  { title: '操作', dataIndex: 'action', width: '180px',scopedSlots: { customRender: 'action' }}
]
const columnsService = [
  { title: '所属组织机构', dataIndex: 'orgName', width: '200px',ellipsis: true },
  { title: '所属项目', dataIndex: 'projectName',width: '200px',ellipsis: true },
  { title: '技术服务名称', dataIndex: 'technicalServerName',width: '200px',ellipsis: true },
  { title: '技术服务类型', dataIndex: 'technicalServerType',width: '200px',ellipsis: true },
  { title: '服务时间', dataIndex: 'serviceTime',width: '200px',ellipsis: true },
  { title: '服务评价', dataIndex: 'evaluationId',width: '200px',ellipsis: true,scopedSlots: { customRender: 'evaluationId' },ellipsis: true},
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectProject,
    BSelect,
    SelectSubCompany,
    ASelectOrgPeople,
    SelectPersonByProject,
    DialogForm
  },
  data() {
    this.columns = columns
    this.columnsService = columnsService
    return {
    queryParam: {}, // 查询参数
    loadData: async (parameter) => {
        if(this.editModel!==2){
         this.queryParam.expertId = this.expertId;
        //this.queryParam.expertId = '000e681b59b04c55a1283948b29fe75a';
        const requestParameters = Object.assign({}, parameter, { query: this.queryParam })
          return getSerDataList(requestParameters).then((res) => {
            return res;
          })
        }
      },
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {branchComName:'',projectName:'',expertName:'',workExperienceList: [], curId: '', supportOrgId: ''}, // 表单
      workForm:{},
      getDetailProjectId:null,
      id: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      querCompany:[],
      visible: {
        visibleWork: false
      },
      rules: {
        curId: [{ required: true, message: '请选择', trigger: 'change' }],
        remark: [{ min: 1, max: 20, message: '长度不得超过20字', trigger: 'blur' }],
        expertUserId:[{ required: true, message: '请选择姓名', trigger: 'change' }],
        inTime: [{ required: true, message: '请选择入组时间', trigger: 'change' }],
      }, // 校验规则
      rulesWork:{
        monitoringTime:[{ required: true, message: '请选择起止时间', trigger: 'change' }],
        workOrgInfo: [{ required: true, message: '请输入工作单位', trigger: 'blur' },],
        jobTitle: [{ required: true, message: '请输入职务', trigger: 'blur' },],
      },
      init: false, // 初始化控件
    }
  },
  watch:{
    'form.supportOrgId'(val) {
      // let supportOrgName = ''
      // if (val) {
      //   supportOrgName = this.querCompany.find((item) => item.id === val).name
      //   this.$set(this.form, 'supportOrgName', supportOrgName)
      //   this.form.supportOrgName = supportOrgName
      // }
    },
  },
  async mounted() {
      this.querCompanyFn();
    if ( this.editModel*1!== 2) {
         await this.getDetailData();

      }else{
        this.form.expertType = this.expertType;
      }
    this.$route.meta.title = ['专家委员会管理 查看', '专家委员会管理 编辑', '专家委员会管理 新增'][this.editModel]

  },
  computed: {
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'curId',
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst:false,
          isNeedAuth:true,
          checkStrictly: false,
          disabled: this.editModel == 0,
          needTags: ['CO', "BC", "PD"],
          isQueryProjecDetail: false
        },
         //  {
         //  type: 'a-select',
         //  keyName: 'supportOrgId',
         //  label: '所属组织机构',
         //  data: this.querCompany,
         //  placeholder:'请选择所属组织机构',
         //  disabled: this.editModel == 0,
         //  replaceFields: {
         //    label: 'name',
         //    value: 'id'
         //  },
         //  change: (e) => {
         //    console.log(e)
         //  }
         // },
         //  {
         //    type: SelectProject,
         //    keyName: 'projectId',
         //    viewName: 'projectName',
         //    disabled: this.editModel == 0,
         //    placeholder:'请选择所属项目',
         //    label: '所属项目',
         //    attrs: {
         //      // keyValue: 'supportOrgId',
         //      // isClear: this.editModel == 2,
         //      // isEdit: this.editModel != 2,
         //      // form: this.form
         //       //isDefaultSelected:true,
         //    autoSelected:false,
         //    keyValue: 'supportOrgId',
         //    isClear: this.editModel == 2,
         //    isEdit: this.editModel != 2,
         //    form: this.form,
         //    //isSelf:false,
         //    },
         //  selectChange: (e) => {
         //    this.$set(this.form, 'projectDeptId', e?.projectDeptId)
         //        if(this.editModel===1 && (e.code!== this.getDetailProjectId)){   // 编辑时，默认不能清空数据
         //          this.form.expertName = ''
         //          this.form.sexInfo = ''
         //          this.form.phoneNum = ''
         //          this.form.jobTitle = ''
         //          this.form.jobName =  ''
         //          this.form.sexInfo =  ''
         //          this.form.firstEducation =  ''
         //          this.form.secEducation =  ''
         //          this.form.topEduProfessional =  ''
         //          this.form.age =  ''
         //          this.form.jobStatusId = ''
         //          this.form.expertId =null
         //          this.form.expertName = null
         //        }
         //
         //      }
         //  },
          {
            keyName: 'expertType',
            type: 'BaseInput',
            disabled:true,
            label: '专家类别',
            placeholder: '自动带出列表左侧选中项',
           },
            {
              type: ASelectOrgPeople,
              keyName: 'expertUserId',
              label: '姓名',
              disabled: this.editModel == 0,
              placeholder: '请选择姓名',
              attrs: {
                init: false,
                keyValue: this.form.projectId?'projectDeptId':'supportOrgId',
               },
              onSelectChange: e => {
                  this.form.expertName = e.name
                  this.form.expertId = e.id
                  this.form.sexInfo = e.sex
                  this.form.phoneNum = e.phone
                  this.form.jobName = e.jobTitle
                  this.form.sexInfo = e.sex
                  this.form.firstEducation = e.firstEducation
                  this.form.secEducation = e.secondEducation
                  this.form.topEduProfessional = e.specialitieMax
                  let postArr = e.postPNames || [],
                  stringArr = []
                   if(postArr.length>0){
                      postArr.map((item)=>{
                        let indexItem  = item.split('/'),
                        last = indexItem.length>0?indexItem[indexItem.length-1]:null;
                        stringArr.push(last)
                      })
                   }
                 this.form.jobTitle = stringArr.length>0?stringArr.join(','):'';
                 this.form.age = e.age
                 this.form.jobStatusId =e.status;
                }
            },
          {
            keyName: 'inTime',
            type: 'a-month-picker',
            disabled: this.editModel == 0,
            label: '入组时间',
            attrs: {
                valueFormat: 'YYYY-MM'
            }
        },
        {
          keyName: 'sexInfo',
          type: 'a-select',
          disabled:true,
          label: '性别',
          data:genderList,
          placeholder: '自动带出',
         },
        {
          keyName: 'phoneNum',
          type: 'a-input',
          disabled:true,
          label: '电话号码',
          placeholder: '自动带出',
         },
         {
          keyName: 'jobTitle',
          type: 'a-input',
          disabled:true,
          label: '职务',
          placeholder: '自动带出',
         },
         {
          keyName: 'jobName',
          type: 'a-input',
          disabled:true,
          label: '职称',
          placeholder: '自动带出',
         },
         {
          keyName: 'firstEducation',
          type: 'a-select',
          disabled:true,
          label: '第一学历',
          placeholder: '自动带出',
          data:educationList
         },
        {
          keyName: 'secEducation',
          type: 'a-select',
          disabled:true,
          label: '第二学历',
          placeholder: '自动带出',
          data:educationList
         },
         {
          keyName: 'topEduProfessional',
          type: 'a-input',
          disabled:true,
          label: '最高学历专业',
           placeholder: '自动带出',
         },
        {
          keyName: 'age',
          type: 'a-input',
          disabled:true,
          label: '年龄',
          placeholder: '自动带出',
        },
        {
          keyName: 'jobStatusId',
          type: 'a-select',
          disabled:true,
          label: '状态',
          data:jobStatusList,
           placeholder: '自动带出',
        },
        {
          keyName: 'remark',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '备注',
          placeholder: '限20字',
         },
      ]
    },
    formListTwo(){
      return [
        {
          keyName: 'personPerformanceInfo',
          type: 'BaseTextarea',
          disabled: this.editModel == 0,
          label: '个人业绩及成果',
          placeholder: '限1000字',
          span: 24,
          autoSize:{ minRows: 10, maxRows: 10 },
          attrs: {
              maxLength : 1000,
            },
        },
      ]
    },
    formListWork(){
      return[
        {
          keyName: 'monitoringTime',
          type: 'a-range-picker',
          placeholder: ['请选择日期', '请选择日期'],
          disabled: this.editModel == 0,
          label: '起止时间',
          span: 22,
            attrs: {
              valueFormat: 'YYYY-MM',
              format: 'YYYY-MM',
            }
        },
        {
          keyName: 'workOrgInfo',
          type: 'BaseInput',
          label: '工作单位',
          span: 22,
        },
        {
          keyName: 'jobTitle',
          type: 'BaseInput',
          label: '职务',
          span: 22,
        },
      ]
    }
  },
  methods: {
    getProjectInfo() {
               this.form.expertName = ''
               this.form.sexInfo = ''
               this.form.phoneNum = ''
               this.form.jobTitle = ''
               this.form.jobName =  ''
               this.form.sexInfo =  ''
               this.form.firstEducation =  ''
               this.form.secEducation =  ''
               this.form.topEduProfessional =  ''
               this.form.age =  ''
               this.form.jobStatusId = ''
               this.form.expertId =null
               this.form.expertName = null
    },
    selectOrg(val) {
      if(val.length === 1 || val.length === 2) {
        this.$set(this.form, 'supportOrgName', val[val.length - 1].orgName)
        this.form.supportOrgId = val[val.length - 1].orgId
      } else if(val.length > 2) {
        this.$set(this.form, 'supportOrgName', val[val.length - 2].orgName)
        this.form.supportOrgId = val[val.length - 2].orgId
        this.form.projectId = val[val.length - 1].projectId
      }
      this.$refs.ruleForm.clearValidate('curId')
    },
   getEvaluationName(data){
      let name = '';
      if(data*1===0){
        name = 'A(非常满意)';
      }else if(data*1===1){
        name = 'B(较满意)';
      }else if(data*1===2){
        name = 'C(一般)';
      }else{
        name = '';
      }
      return name;
   },
    querCompanyFn() {
      let userInfo = JSON.parse(sessionStorage.getItem('ycloud-user_info')),
      currentPost = userInfo?.currentPost ||{};
      this.querCompany = [];
        return getAllBranchCompany({tagCodes: ['BC']}).then((res) => {
        let co = [{
            id: "53085e2c9f1f4685801ef31994f57c49",
            name: "总部机关",
        }]
        res.data = [ ...co, ...res.data ]
        if(currentPost.code !== 'CO'){
             this.querCompany.push({
               name:currentPost.orgName,
               id:currentPost.orgId
             })
        }else{
          this.querCompany = res.data
        }
        })
    },
  delwork(index){
    this.form.workExperienceList.splice(index, 1)
  },
  confirmWork(data){
     this.form.workExperienceList.push(data);
     this.visible.visibleWork = false;
  },
  handleOk(){
   this.$refs.dialogForm.handleOk()
  },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }else {
          this.$message.warning('请填写完所有必填项信息')
        }
      })
      return flag
    },
    getDetailData() {
      // 不为添加时请求详情
      if (this.editModel != 2) {
        this.loading = true
        getExpertDetail({ id: this.id })
          .then((res) => {
            this.loading = false
            res.data.jobStatusId =  res.data.jobStatusId*1;
            this.form = { ...this.form, ...res.data }
            if(this.form.projectId) {
              this.form.curId = this.form.projectId
            } else {
              this.form.curId = this.form.supportOrgId
            }
            this.getDetailProjectId = res.data.projectId;
            if(!this.form.workExperienceList){
              this.form.workExperienceList = [];
            }
            if(this.form.workExperienceList.length>0){
              this.form.workExperienceList.map((item)=>{
                 item.monitoringTime = [item.beginTime,item.endTime]
              })
            }
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.$nextTick(() => {
          this.init = true
        })
      }
    },
    /**
     * 设置在职状态名称
     */
    getStatusName(status){
       let statusName = jobStatusList.find((item)=>item.value*1 ===status*1) || null;
       if(statusName){
        this.$set(this.form, 'jobStatus', statusName.label)
       }
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      this.form.expertTypeId = this.expertTypeId;
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      this.loading = true
      this.loadingBtn[status] = true
      this.form.jobStatusId && this.getStatusName(this.form.jobStatusId)
      let form = this.$clone(this.form)
      let workExperienceListTime = form.workExperienceList;
      if(workExperienceListTime.length>0){
         workExperienceListTime.map((item)=>{
           item.beginTime = item.monitoringTime[0];
           item.endTime = item.monitoringTime[1]
         })
      }
      let api = addExpert
      api(form)
        .then(() => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          this.$multiTab.close()
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
